package com.lfc.myframe.utils

import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.content.Context.ACTIVITY_SERVICE
import android.content.Intent
import android.graphics.Color
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat.startActivity
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lfc.myframe.share.Const.Data_FileDirPath
import com.lzy.ninegrid.ImageInfo
import com.lzy.ninegrid.preview.ImagePreviewActivity
import org.greenrobot.eventbus.EventBus
import org.json.JSONArray
import java.io.*


/**
 * Created by LFC
on 2021-10-11.
 */
class MAFWUtils {
    companion object {


        /**
         * 添加搜索记录
         */
        /*      fun putSearchHis(baseContext: Context, str: String) {
                  var shBox = ObjectBox.boxStore.boxFor(SearchInfo::class.java)
                  var shInfo = SearchInfo()
                  shInfo.strNmae = str
                  try {
                      shBox?.put(shInfo)
                  } catch (e: Exception) {
                      e.printStackTrace()
                  }
              }

              fun ClearSearchHis(baseContext: Context) {
                  var shBox = ObjectBox.boxStore.boxFor(SearchInfo::class.java)
                  shBox?.removeAll()
              }

              fun SearchHisAll(baseContext: Context): MutableList<SearchInfo> {
                  var shBox = ObjectBox.boxStore.boxFor(SearchInfo::class.java)
                  var list: MutableList<SearchInfo>? = mutableListOf()
                  list = shBox?.query()?.build()?.find()
                  if (list.isNullOrEmpty()) {
                      return mutableListOf<SearchInfo>()

                  } else
                      return list
              }*/


        fun String2Double(strvalue: String = ""): Double {
            var dResult = 0.0
            if (strvalue.isNotBlank()) dResult = strvalue.toDouble()
            return dResult
        }

        fun setEtDelImg(et: EditText, imgdel: ImageView) {
            et.addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    if (s.toString().trim().isNotBlank()) {
                        imgdel.visibility = View.VISIBLE
                    } else {
                        imgdel.visibility = View.INVISIBLE
                    }
                }

                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                }

            })
        }

        fun toSelfSetting(context: Activity) {
            var mIntent = Intent();
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 9) {
                mIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                mIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
            } else if (Build.VERSION.SDK_INT <= 8) {
                mIntent.setAction(Intent.ACTION_VIEW);
                mIntent.setClassName(
                    "com.android.settings",
                    "com.android.setting.InstalledAppDetails"
                );
                mIntent.putExtra(
                    "com.android.settings.ApplicationPkgName",
                    context.getPackageName()
                )
            }
            context.startActivity(mIntent)
        }


        /**
         * 毫秒
         */
        fun formatMusicTime(duration: Long): String {
            var time = ""
            val minute = duration / 60000
            val seconds = duration % 60000
            val second = Math.round(seconds.toInt() / 1000.toFloat()).toLong()
            if (minute < 10) {
                time += "0"
            }
            time += "$minute:"
            if (second < 10) {
                time += "0"
            }
            time += second
            return time
        }


        /**
         * 字符串截取变红
         *
         * @param  ，可为null
         * @param string2 你要变色的字符
         * @param string 整个字符串
         * @param numtext
         */
        fun StringInterceptionChangeRed(
            numtext: TextView,
            string: String, string2: String
        ) {
            if (!string.contains(string2)) {
                numtext.setText(string)
                return

            }
            val fstart = string.indexOf(string2)
            val fend = fstart + string2.length
            if (fend != 0 && fstart != -1) {
                val style = SpannableStringBuilder(string)
                style.setSpan(
                    ForegroundColorSpan(Color.parseColor("#0087FF")), fstart, fend,
                    Spannable.SPAN_EXCLUSIVE_INCLUSIVE
                )
                numtext.setText(style)
            }
        }


        /*
 * 从Apk本地Assets复制文件到指定文件夹
 *
 */
        fun copyFileFromAssets(context: Activity): Boolean {
            var result = false
            //手机更目录创建MP3Test文件夹
            val filepath: String = Data_FileDirPath + File.separator
//            Environment.getExternalStorageDirectory().getAbsolutePath().toString() + "/MP3Test/"
            //这是放在私有文件夹里
            //String filepath = this.getApplicationContext().getFilesDir().getAbsolutePath() + "/oneLing.mp3";
            Log.i("filepath", "copyFileFromAssets: $filepath")
            val fileName = "aliyundownkey.dat" //文件名称
            val dir = File(filepath)
            Log.i("path", "copyData: $filepath")
            val file = File(dir, fileName)
            if (!dir.exists() || !dir.isDirectory) {
                dir.mkdirs()
            }
            var inputStream: InputStream? = null
            var outputStream: OutputStream? = null
            if (!file.exists()) {
                try {
                    file.createNewFile()
                    inputStream = context.getAssets().open(fileName)
                    outputStream = FileOutputStream(file)
                    val buffer = ByteArray(1024)
                    var len: Int
                    while (inputStream.read(buffer).also { len = it } != -1) {
                        outputStream.write(buffer, 0, len)
                    }
                    outputStream.flush()
                    outputStream.close()
                    inputStream.close()
                    result = true
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            } else {
                try {
                    file.delete()
                    file.createNewFile()
                    inputStream = context.getAssets().open(fileName)
                    outputStream = FileOutputStream(file)
                    val buffer = ByteArray(1024)
                    var len: Int
                    while (inputStream.read(buffer).also { len = it } != -1) {
                        outputStream.write(buffer, 0, len)
                    }
                    outputStream.flush()
                    outputStream.close()
                    inputStream.close()
                    result = true
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            return result
        }


        /**
         * 判断应用是否在运行
         * @param context
         * @return
         */
        fun isRun(context: Context): Boolean {
            val am =
                context.getSystemService(ACTIVITY_SERVICE) as ActivityManager
            val list: List<ActivityManager.RunningTaskInfo> = am.getRunningTasks(100)
            var isAppRunning = false
            val MY_PKG_NAME = context.packageName
            //100表示取的最大的任务数，info.topActivity表示当前正在运行的Activity，info.baseActivity表系统后台有此进程在运行
            for (info in list) {
                if (info.topActivity?.getPackageName()
                        .equals(MY_PKG_NAME) || info.baseActivity?.getPackageName()
                        .equals(MY_PKG_NAME)
                ) {
                    isAppRunning = true
                    Log.i(
                        "ActivityService isRun()",
                        info.topActivity?.getPackageName()
                            .toString() + " info.baseActivity.getPackageName()=" + info.baseActivity?.getPackageName()
                    )
                    break
                }
            }
            Log.i(
                "ActivityService isRun()",
                "com.ad 程序  ...isAppRunning......$isAppRunning" + " list.size:" + list.size
            )
            return isAppRunning && list.size > 1
        }


        /**
         * 大图查看
         */
        fun showBigImgs(
            context: Context,
            pathList: MutableList<String>,
            rlv: RecyclerView,
            index: Int
        ) {

            val imageInfo = ArrayList<ImageInfo>()
            if (pathList != null) {
                for (imageString in pathList) {
                    val info = ImageInfo()
                    info.setThumbnailUrl(imageString)
                    info.setBigImageUrl(imageString)
                    imageInfo.add(info)
                }
            }
            Log.e("UserAlbumRclAdapter", "imageInfo:" + imageInfo.size)

            for (i in imageInfo.indices) {
                val info = imageInfo[i]
                val imageView: View
                if (i < imageInfo.size) {
                    imageView = rlv.getChildAt(i)
                } else {
                    //如果图片的数量大于显示的数量，则超过部分的返回动画统一退回到最后一个图片的位置
                    imageView = rlv.getChildAt(imageInfo.size - 1)
                }
                info.imageViewWidth = imageView.width
                info.imageViewHeight = imageView.height
                val points = IntArray(2)
                imageView.getLocationInWindow(points)
                info.imageViewX = points[0]
                info.imageViewY = points[1] - getStatusHeight(context)
            }

            val intent = Intent(context, ImagePreviewActivity::class.java)
            val bundle = Bundle()
            bundle.putSerializable(ImagePreviewActivity.IMAGE_INFO, imageInfo as Serializable)
            bundle.putInt(ImagePreviewActivity.CURRENT_ITEM, index)
            intent.putExtras(bundle)
            context.startActivity(intent)
        }

        fun showSingleBigImgs(
            context: Context,
            strUrls: String,
            index: Int = 0
        ) {

            val imageInfo = ArrayList<ImageInfo>()
            val info = ImageInfo()
            info.setThumbnailUrl(strUrls)
            info.setBigImageUrl(strUrls)
            imageInfo.add(info)
            Log.e("UserAlbumRclAdapter", "imageInfo:" + imageInfo.size)

            val intent = Intent(context, ImagePreviewActivity::class.java)
            val bundle = Bundle()
            bundle.putSerializable(ImagePreviewActivity.IMAGE_INFO, imageInfo as Serializable)
            bundle.putInt(ImagePreviewActivity.CURRENT_ITEM, index)
            intent.putExtras(bundle)
            context.startActivity(intent)
        }

        /**
         * 获得状态栏的高度
         */
        fun getStatusHeight(context: Context): Int {
            var statusHeight = -1
            try {
                val clazz = Class.forName("com.android.internal.R\$dimen")
                val `object` = clazz.newInstance()
                val height =
                    Integer.parseInt(clazz.getField("status_bar_height").get(`object`).toString())
                statusHeight = context.resources.getDimensionPixelSize(height)
            } catch (e: Exception) {
                e.printStackTrace()
            }

            return statusHeight
        }

        fun <T> jsonToList(jsonList: String): List<T> {
            return Gson().fromJson(jsonList, object : TypeToken<ArrayList<T>>() {}.type)
        }

        fun <T> jsonToDto(
            message: String?,
            cls: Class<T>?
        ): List<T>? { //这里是Class<T>
            val jsonArray = JSONArray(message)
            val gson = Gson()
            val list: MutableList<T> = ArrayList()
            for (index in 0 until jsonArray.length()) {
                list.add(gson.fromJson(jsonArray[index].toString(), cls)) //cls

            }
            return list
        }
    }


}